function getSiteCfg() { 
    $.getJSON(
        "/api/ocie/config_public/",
        function(json){
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.ocie_poc_email + '">' + json.ocie_poc_name + '</a> ' +
                      'Phone: (' + json.ocie_poc_phone.substr(0,3) + ') ' +
                      json.ocie_poc_phone.substr(3,3) + '-' + 
                      json.ocie_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    );
    $.ajax({
        type: "GET",
        url: "/api/ocie/role_check/",
        success: function(string){
            $("a.logout:contains(Options)").css("display","block");
        },
        error: function(string){
            window.location = "/ocie/";
        }
    });
}


function getCommonLookups() {
    $.ajax({
        type: 'GET',
        url: '/api/ocie/common_lookups/',
        dataType: "json",
        success: function(json){
            jQuery.map(json.appointment_types, function(i){
                $("select[name='$AppointmentType']").append('<option value="' + i.appointment_type_id + '">' + i.description + '</option>'); 
	    });
            jQuery.map(json.units, function(i){
                $("select[name='$Unit']").append('<option value="' + i.unit_id + '">' + i.description + '</option>'); 
	    });
            setProtoHTML();
            getReports();
        },
        error: function(string){
            if(string.status >= 400 && string.status < 500){
                window.location = "/ocie/";
            }
        }
    });
}


function getReports() {
    $.getJSON('/api/ocie/reports/', function(json){
        $("#reportsTable tbody").remove();
        if(json.length == 0){ $("#reportsTable").append(proto_html['no_reports']); }
        jQuery.map(json, function(i){
            $("#reportsTable").append(proto_html['display_row']);
            $("#reportsTable tbody:last tr:eq(0) td:eq(0) h5").html(i.report_id);
            $("#reportsTable tbody:last tr:eq(0) td:eq(1) h5").html(i.title);
            $("#reportsTable tbody:last tr:eq(0) td:eq(2)").html( buildCustomFields(i.query) );
            $("#reportsTable tbody:last").hover(
                function () { $(this).addClass('highlight'); },
                function () { $(this).removeClass('highlight'); }
            );
            $("#reportsTable tbody:last tr:eq(0) td:eq(3) a:eq(0)").click( function () {
                $("#reportsTable tbody, td, a").unbind();
                var field_list = $(this).parents("tr").children("td:nth-child(3)").children(":input");
                writeReport(i.report_id, field_list, i.title, 'write');
                return false;
            });
            $("#reportsTable tbody:last tr:eq(0) td:eq(3) a:eq(1)").click( function () {
                $("#reportsTable tbody, td, a").unbind();
                var field_list = $(this).parents("tr").children("td:nth-child(3)").children(":input");
                writeReport(i.report_id, field_list, i.title, 'print');
                return false;
            });
            $("#reportsTable tbody:last tr:eq(0) td:lt(2)").click( function () {
                $("#reportsTable td:nth-child(3) :input").attr({disabled: "true"});
                $("#reportsTable a").addClass('buttonInactive');
                $("#reportsTable tbody, td, a").unbind();
                $(this).parents("tbody").replaceWith(proto_html['edit_row']);
                $("#reportsTable td:nth-child(4) a").click( function () { return false; });
                $("#reportsTable tbody:has(tr:eq(1))").addClass('highlight');
                fillReportValues(i);
                $("#button_div a").unbind();
                $("#button_div a").click( function () { return false; });
                $("#button_div a").addClass('buttonInactive');
                return false;
            });
	});
	$("#reportsTable > tbody:odd").addClass('tableAlternateColor');
        $("#button_div").html(proto_html['button_add']);
	$("#button_div a").click( function () { 
	    buildAddReport();
	    return false;
        });
    });
}


var putReport = function() {
    var url = '/api/ocie/reports/';
    var request_method = 'PUT';
    return formSubmit(request_method, url);
}


var postReport = function(report_id) {
    var url = '/api/ocie/reports/' + report_id + '/';
    var request_method = 'POST';
    return formSubmit(request_method, url);
}


function formSubmit(request_method, url) {
    report_data = {};
    report_data['title'] = $("#reportsTable :input[name='title']").val();
    report_data['description'] = $("#reportsTable :input[name='description']").val();
    report_data['query'] = $("#reportsTable :input[name='query']").val();
    $.ajax({
        type: request_method,
        url: url,
        data: report_data,
        success: function(){ getReports(); },
        error: function(string){
            $("#message").remove();
            if(string.status == 409){
                $("#reportsTable tbody.highlight tr:nth-child(3) td a:last").after('<span id="message" name="message" class="loginGeneralErrorMessage"><img src="/ocie/images/icons/error.gif" alt="" />The query can not contain Insert, Delete, Create or Drop.</span>');    
            }else{
                $("#reportsTable tbody.highlight tr:nth-child(3) td a:last").after('<span id="message" name="message" class="loginGeneralErrorMessage"><img src="/ocie/images/icons/error.gif" alt="" />Unable to save at this time.</span>');
            }
        }
    });
}


function deleteReport(report_id) {
    $.ajax({
        type: 'DELETE',
        url: '/api/ocie/reports/' + report_id + '/',
        success: function(){ getReports(); },
        error: function(){ console.debug('Error'); }
    });
}


function fillReportValues(report) {
    $("#reportsTable tbody.highlight tr:eq(0) td:eq(0) h5").html(report.report_id);
    $("#reportsTable :input[name='title']").val(report.title);
    $("#reportsTable :input[name='description']").val(report.description);
    $("#reportsTable :input[name='query']").val(report.query);
    $("#reportsTable tbody.highlight tr:nth-child(3) td a:nth-child(1)").click( function () {
        $("#message").remove();
        $("#reportsTable tbody.highlight tr:nth-child(3) td a:last").after('<span id="message" name="message" class="loginWaitMessage"><img src="/ocie/images/icons/hourglass.gif" alt="" />Saving...</span>');
        postReport(report.report_id);
        return false;
    });
    $("#reportsTable tbody.highlight tr:nth-child(3) td a:nth-child(2)").click( function () {
        getReports();
        return false;
    });
    $("#reportsTable tbody.highlight tr:nth-child(3) td a:nth-child(3)").click( function () {
        $("#message").remove();
        $("#reportsTable tbody.highlight tr:nth-child(3) td a:last").after('<span id="message" name="message" class="loginWaitMessage"><img src="/ocie/images/icons/hourglass.gif" alt="" />Deleting...</span>');
        deleteReport(report.report_id);
        return false;
    });
}


function buildAddReport() {
    $("#reportsTable tbody, td, a").unbind();
    $("#reportsTable td:nth-child(3) :input").attr({disabled: "true"});
    $("#reportsTable a").addClass('buttonInactive').click( function () { return false; });
    $("#button_div a").unbind();
    $("#button_div a").click( function () { return false; });
    $("#button_div a").addClass('buttonInactive');
    $("#reportsTable thead").after(proto_html['edit_row']);
    $("#reportsTable tbody:has(tr:eq(1))").addClass('highlight');
    $("#reportsTable tbody.highlight tr:nth-child(3) td a:nth-child(3)").remove();
    $("#reportsTable tbody.highlight tr:nth-child(1) td a").click( function () { return false; });
    $("#reportsTable tbody.highlight tr:nth-child(3) td a:nth-child(1)").click( function () {
        $("#message").remove();
        $("#reportsTable tbody.highlight tr:nth-child(3) td a:last").after('<span id="message" name="message" class="loginWaitMessage"><img src="/ocie/images/icons/hourglass.gif" alt="" />Saving...</span>');
        putReport();
        return false;
    });
    $("#reportsTable tbody.highlight tr:nth-child(3) td a:nth-child(2)").click( function () {
        getReports();
        return false;
    });
}


function buildCustomFields(query) {
    var custom_fields = query.match(/\$\w+/gi);
    if(!custom_fields){ return ''; }
    var custom_fields_html = [];
    if( jQuery.inArray('$Unit',custom_fields) != -1 ){
        custom_fields_html[custom_fields_html.length] = proto_html['units'];
        custom_fields = jQuery.grep(custom_fields, function(n, i){ return (n != "$Unit"); });
    }
    if ( jQuery.inArray('$AppointmentType',custom_fields) != -1 ){
        custom_fields_html[custom_fields_html.length] = proto_html['appointment_types'];
        custom_fields = jQuery.grep(custom_fields, function(n, i){ return (n != "$AppointmentType"); });
    }
    if ( jQuery.inArray('$From',custom_fields) != -1 ){
        custom_fields_html[custom_fields_html.length] = proto_html['from_to'];
        custom_fields = jQuery.grep(custom_fields, function(n, i){ return (n != "$From" && n != "$To"); });
    }
    jQuery.map(custom_fields, function(field){
        custom_fields_html[custom_fields_html.length] = '<label>' + field.substring(1) + 
            ':</label> <input name="' + field + '" type="text" size="12" value=""/>';
    });
    return custom_fields_html.join('<br /><br />');
}


function writeReport(report_id, field_list, title, option) {
    field_data = {};
    field_data['GarbageFormField'] = '';
    jQuery.map(field_list, function(field){
        field_data[field.name] = field.value;
    });
    $.ajax({
        type: "POST",
        url: '/api/ocie/report_results/' + report_id + '/',
        data: field_data,
        dataType:"string",
        success: function(string){
            var json = eval("(" + string + ")");
            if(option == 'write'){
                $("#reportsTable").empty();
                $("#reportsTable").append('<caption>' + json.title + '</caption>');
                $("#reportsTable").append(writeReportHeader(json.sections[0].table.headers));
                $("#reportsTable").append(writeReportData(json.sections[0].table.rows, json.sections[0].table.headers.length));
                $("#button_div").html(proto_html['button_pdf']);
	        $("#button_div a").click( function (){
                    postPdfJson(string);
                    return false;
                });       
            }else{
                postPdfJson(string);
            }
        }
    });
}


function writeReportHeader(columns) {
    content = ''
    jQuery.map(columns, function(col){
        content += '<th>' + col + '</th>';
    });
    content = '<thead><tr>' + content + '</tr></thead>'; 
    return content;
}


function writeReportData(data, column_count) {
    content = '';
    if (data.length == 0){
        content += '<tr><td colspan="' + column_count + '">No Results.</td></tr>';
    }else{
        jQuery.map(data, function(data_row){
            content += '<tr>'
            jQuery.map(data_row, function(data_cell){
                content += '<td>' + data_cell + '</td>';            
            });        
            content += '</tr>';
        });
    }
    content = '<tbody>' + content + '</tbody>';
    return content;
}


function postPdfJson(string) {
    var form = document.createElement('form');
    $(form).attr({
            action: '/api/pdf/',
            method: 'post'
        });
    $(form).css('display','none');
    var inp_json = document.createElement('input');
    $(inp_json).attr({
            type: 'hidden',
            name: 'pdf',
            value: string            
        });
    $(form).append(inp_json);
    var inp_template = document.createElement('input');
    $(inp_template).attr({
            type: 'hidden',
            name: 'template',
            value: 'OCIETemplate'            
        });
    $(form).append(inp_template);
    $(document.body).append(form)
    form.submit();
}


function setProtoHTML() {
    var proto_pre = {
        'no_reports':'protoNoReportHTML',
        'display_row':'protoDisplayReportHTML',
        'edit_row':'protoEditReportHTML',
        'appointment_types':'protoAppointmentTypesSelectHTML',
        'units':'protoUnitSelectHTML',
        'from_to':'protoFromToInputHTML',
        'button_pdf':'protoPDFButtonHTML',
        'button_add':'protoAddButtonHTML'
    };
    proto_html = {};
    jQuery.each(proto_pre, function(i, val) {
        proto_html[i] = $("#" + val).html();
        $("#" + val).remove();
    });
}


$(document).ready(function() {
    getSiteCfg();
    getCommonLookups();
});
